package com.resou.reader.dialog.threeDaysrecharge;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.resou.reader.R;
import com.resou.reader.ReSouApplication;
import com.resou.reader.api.entry.PayConfigBean;
import com.resou.reader.api.entry.WXPayBean;
import com.resou.reader.commom.Constant;
import com.resou.reader.mine.paycenter.PayCenterActivity;
import com.resou.reader.mine.paycenter.PayResult;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.log.DLog;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.net.UnknownServiceException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeoutException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class ThreeDaysRechargeDialog extends DialogFragment implements View.OnClickListener, ReaderRechargeContract.View {
    public static final String PRICE = "price";

    @BindView(R.id.iv_back)
    ImageView ivBack;
    Unbinder unbinder;
    @BindView(R.id.ll_we_chat)
    LinearLayout llWeChat;
    @BindView(R.id.ll_ali_pay)
    LinearLayout llAliPay;
    @BindView(R.id.tv_amount)
    TextView tvAmount;
    @BindView(R.id.tv_currency)
    TextView tvCurrency;
    @BindView(R.id.tv_voucher)
    TextView tvVoucher;
    @BindView(R.id.ll_discounts)
    LinearLayout llDiscounts;
    private String mPrice;
    private ReaderRechargePresenter mPresenter;

    public static ThreeDaysRechargeDialog newInstance(String money) {
        Bundle args = new Bundle();
        args.putString(PRICE, money);
        ThreeDaysRechargeDialog fragment = new ThreeDaysRechargeDialog();
        fragment.setArguments(args);
        return fragment;
    }

    private Activity mActivity;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = (Activity) context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mPrice = getArguments().getString(PRICE);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Objects.requireNonNull(getDialog().getWindow()).requestFeature(Window.FEATURE_NO_TITLE);
        View view = inflater.inflate(R.layout.dialog_payment_method, container, false);
        unbinder = ButterKnife.bind(this, view);
        llDiscounts.setVisibility(View.GONE);
        //人民币金额
        tvAmount.setText("¥" + mPrice);

        ivBack.setOnClickListener(this);
        llAliPay.setOnClickListener(this);
        llWeChat.setOnClickListener(this);
        mPresenter = new ReaderRechargePresenter(this);
        mWXAPI = WXAPIFactory.createWXAPI(mActivity, Constant.APP_ID_WE_CHAT, false);
        mWXAPI.registerApp(Constant.APP_ID_WE_CHAT);
        return view;
    }

    private static final String TAG = "ThreeDaysRechargeDialog";

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
//        getDialog().setCanceledOnTouchOutside(false);
        Window win = getDialog().getWindow();
        DisplayMetrics dm = new DisplayMetrics();
        // 一定要设置Background，如果不设置，window属性设置无效
        if (win != null) {
            win.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//        win.setLayout((dm.widthPixels), (int) (dm.heightPixels * 0.5));
            mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
            WindowManager.LayoutParams params = win.getAttributes();
            params.windowAnimations = R.style.bottomSheet_animation;
            params.gravity = Gravity.BOTTOM;
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
            win.setAttributes(params);
            // 使用ViewGroup.LayoutParams，以便Dialog 宽度充满整个屏幕
//        params.height = (int) (dm.heightPixels * 0.5);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onClick(View v) {
        if (v == ivBack) {
            dismiss();
        }
        if (v == llAliPay) {
            mPresenter.fetchAliPayOrderInfo(mPrice);
//           onAliPayClicked(mPayConfigBean);
        }
        if (v == llWeChat) {
//            mInteractionListener.onWeChatClicked(mPayConfigBean);
            boolean isWeChatInstall = UMShareAPI.get(ReSouApplication.getRSApplication()).isInstall(mActivity, SHARE_MEDIA.WEIXIN);
            if (isWeChatInstall) {
                mPresenter.fetchWXOrderInfo(mPrice);
            } else {
                ToastUtil.makeShortToast("您还未安装微信");
            }
        }
        dismiss();
    }


    @Override
    public void initData() {

    }

    @Override
    public void showContent() {

    }

    @Override
    public void showProgress() {

    }

    @Override
    public void showError(Throwable throwable) {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
        if (throwable instanceof UnknownHostException
                || throwable instanceof UnknownServiceException
                || throwable instanceof TimeoutException || throwable instanceof ConnectException) {
            QMUITipDialog dialog = new QMUITipDialog.Builder(mActivity)
                    .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)
                    .setTipWord("请检查网络状况")
                    .create();
            dialog.show();
            new Handler().postDelayed(dialog::dismiss, 1000);
        } else {
            QMUITipDialog dialog = new QMUITipDialog.Builder(mActivity)
                    .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)
//                    .setTipWord("未知错误")
                    .setTipWord(throwable.getMessage())
                    .create();
            dialog.show();
            new Handler().postDelayed(dialog::dismiss, 1000);
        }
    }

    @Override
    public void showEmpty() {

    }

    private QMUITipDialog mDialog;

    @Override
    public void showLoadingIndicator() {
        mDialog = new QMUITipDialog.Builder(mActivity)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("加载中")
                .create();
        mDialog.show();
    }

    @Override
    public void hideLoadingIndicator() {
        mDialog.dismiss();
    }

    private static final int SDK_PAY_FLAG = 1;

    @Override
    public void invokeAliPay(String orderInfo) {
        final Runnable payRunnable = () -> {
            PayTask alipay = new PayTask(mActivity);
            Map<String, String> result = alipay.payV2(orderInfo, true);
//            Log.i("msp111", result.toString());

            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private IWXAPI mWXAPI;
    private PayReq request = new PayReq(); //调起微信APP的对象

    @Override
    public void invokeWXPay(WXPayBean wxPayBean) {
        if (wxPayBean == null) {
            DLog.d(PayCenterActivity.class.getSimpleName(), "wxPayBean == null!!");
            return;
        }

        request.appId = wxPayBean.getAppid();
        request.partnerId = wxPayBean.getMch_id();
        request.prepayId = wxPayBean.getPrepay_id();
        request.packageValue = "Sign=WXPay";
        request.nonceStr = wxPayBean.getNonce_str();
        request.timeStamp = wxPayBean.getTimestamp();
        request.sign = wxPayBean.getSign();

        mWXAPI.sendReq(request);//发送调起微信的请求
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /*
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastUtil.makeLongToast("支付成功");
                        dismiss();
                    } else if (TextUtils.equals(resultStatus, "4000")) {
                        ToastUtil.makeLongToast("支付失败");
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    } else if (TextUtils.equals(resultStatus, "6001")) {
                        ToastUtil.makeLongToast("支付取消");
                    } else if (TextUtils.equals(resultStatus, "6002")) {
                        ToastUtil.makeLongToast("网络连接出错");
                    }

//                    9000	订单支付成功
//                    8000	正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
//                    4000	订单支付失败
//                    5000	重复请求
//                    6001	用户中途取消
//                    6002	网络连接出错
//                    6004	支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
//                    其它	其它支付错误
                    break;
                }
                default:
                    break;
            }
        }
    };

    public interface OnPaymentDialogInteractionListener {
        void onAliPayClicked(PayConfigBean payConfigBean);

        void onWeChatClicked(PayConfigBean payConfigBean);
    }
}
